package com.xiaojie.dubbo.server.loadBalance;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 权重算法
 * @author: xiaojie
 * @date: 2021.08.06
 */
public class WeightBalance  implements  LoadBalance<Weight>{
    List<Weight> weightsList=new ArrayList<>();
    //定义全局
    static int index=0;
    @Override
    public String select(List<Weight> repos) {
        if (repos==null||repos.size()<0){
            throw  new RuntimeException("repos is null");
        }
        for ( int i=0;i<repos.size();i++){
            for (int j=0;j<repos.get(i).getScore();j++){
                weightsList.add(repos.get(i));
            }
        }
        if (index>= weightsList.size()){
            index=0;
        }
        String  value = weightsList.get(index++).getHost();
        System.out.println("value:"+value);
        return value;
    }

    public static void main(String[] args) {
        LoadBalance weightBalance = new WeightBalance();
        ArrayList<Weight> weights=new ArrayList<>();
        weights.add(new Weight("127.0.0.1:8080",1));
        weights.add(new Weight("127.0.0.1:8081",1));
        weights.add(new Weight("127.0.0.1:8082",2));
        weightBalance.select(weights);
        weightBalance.select(weights);
        weightBalance.select(weights);
        weightBalance.select(weights);
    }
}


/*
 * 权重的实体类
 * @param null 
 * @todo
 * @author xiaojie 
 * @date 2021/8/6 11:15 
 * @return 
 */
class  Weight{
    //地址
    private String host;
    //权重
    private Integer score;

    public Weight(String host, Integer score) {
        this.host = host;
        this.score = score;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }
}